// ********************************** Upload ********************** //
var uploader, fileList;
/**
 * create a upload area
 *
 * @param string container container to create upload
 * @params object file, size, status, callback
 *
 * @returns
 */
var yuiInitUploader = function (container, config) {
    this.txt_file = config.file ? config.file : 'File';
    this.txt_size = config.size ? config.size : 'Size';
    this.txt_status = config.status ? config.status : 'Status';
    this.callback = config.callback ? config.callback : null;
    this.fitSize = function () {
        YAHOO.util.Dom.setStyle(this.overlay, 'width', this.uiRegion.width + "px");
        YAHOO.util.Dom.setStyle(this.overlay, 'height', this.uiRegion.height + "px");
    };
    this.hideFileHandlerActions = function () {
        var els = YAHOO.util.Dom.getElementsByClassName('yuiUploadBtn', null, this.uiLayer);
        YAHOO.util.Dom.setStyle(els, 'display', 'none');
    };
    this.container = container;
    // Instantiate the uploader and write it to its placeholder div.
    this.uiLayer = YAHOO.util.Dom.get(container);
    // get cont. of select files field
    var els = YAHOO.util.Dom.getElementsByClassName('yuiUploadSelect', null, this.container);
    this.uiRegion = YAHOO.util.Dom.getRegion(els[0]);
    // get Upload element
    var tmp = YAHOO.util.Dom.getElementsByClassName('yuiUpload', '', this.container);
    this.overlay = tmp[0];
    this.fitSize();
    var elId = this.overlay.id;
    if (!elId)
        elId = YAHOO.util.Dom.generateId(this.overlay);
    uploader = new YAHOO.widget.Uploader(elId);
    uploader.parentObject = this;
    // Add event listeners to various events on the uploader.
    // Methods on the uploader should only be called once the
    // contentReady event has fired.

    uploader.addListener('contentReady', handleContentReady);
    uploader.addListener('fileSelect', onFileSelect);
    uploader.addListener('uploadStart', onUploadStart);
    uploader.addListener('uploadProgress', onUploadProgress);
    uploader.addListener('uploadCancel', onUploadCancel);
    uploader.addListener('uploadComplete', onUploadComplete);
    uploader.addListener('uploadCompleteData', onUploadResponse);
    uploader.addListener('uploadError', onUploadError);
    uploader.addListener('rollOver', handleRollOver);
    uploader.addListener('rollOut', handleRollOut);
    uploader.addListener('click', handleClick);
    // this.hideFileHandlerActions();
};


// When the mouse rolls over the uploader, this function
// is called in response to the rollOver event.
// It changes the appearance of the UI element below the Flash overlay.
function handleRollOver() {
}

// On rollOut event, this function is called, which changes the appearance of
// the
// UI element below the Flash layer back to its original state.
function handleRollOut() {
}

// When the Flash layer is clicked, the "Browse" dialog is invoked.
// The click event handler allows you to do something else if you need to.
function handleClick() {
}

// When contentReady event is fired, you can call methods on the uploader.
function handleContentReady() {
//    var ff = new Array( {
//        description : "Images",
//        extensions : "*.jpg;*.gif;*.png"
//    });
    // Allows multiple file selection in "Browse" dialog.
    try {
        uploader.setAllowMultipleFiles(true);
        // Apply new set of file filters to the uploader.
        if (typeof fileUploadAllowed == 'object')
            uploader.setFileFilters(fileUploadAllowed);
    } catch (e) {
        //uploader._loadHandler();
        // alert ('yuiUploader Failed: ' + e);
    }
}

// Actually uploads the files. In this case,
// uploadAll() is used for automated queueing and upload
// of all files on the list.
// You can manage the queue on your own and use "upload" instead,
// if you need to modify the properties of the request for each
// individual file.
function yuiUploaderUpload(path) {
    if (fileList != null) {
        uploader.setSimUploadLimit(1);
        uploader.uploadAll(path);
    }
}

// Fired when the user selects files in the "Browse" dialog
// and clicks "Ok".
function onFileSelect(event) {
    if('fileList' in event && event.fileList != null) {
        fileList = event.fileList;
        createDataTable(fileList);
    }
}

function createDataTable(entries) {
    rowCounter = 0;
    this.fileIdHash = {};
    this.dataArr = [];
    for ( var i in entries) {
        // yuiHumanReadableFileSize
        var entry = entries[i];
        entry["progress"] = "<div style='height:5px;width:100px;background-color:#CCC;'></div>";
        dataArr.unshift(entry);
    }
    for ( var j = 0; j < dataArr.length; j++) {
        dataArr[j].size = yuiHumanReadableFileSize(dataArr[j].size);
        this.fileIdHash[dataArr[j].id] = j;
    }
    var myColumnDefs = [ {
        key : "name",
        label : uploader.parentObject.txt_file,
        sortable : false
    }, {
        key : "size",
        label : uploader.parentObject.txt_size,
        className: 'alignRight',
        sortable : false
    }, {
        key : "progress",
        label : uploader.parentObject.txt_status,
        sortable : false
    } ];

    this.myDataSource = new YAHOO.util.DataSource(dataArr);
    this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
    this.myDataSource.responseSchema = {
        fields : [ "id", "name", "created", "modified", "type", "size", "progress" ]
    };
    this.singleSelectDataTable = new YAHOO.widget.DataTable("yuiUploadDataTableContainer", myColumnDefs, this.myDataSource, {
        selectionMode : "single"
    });
}

// Do something on each file's upload start.
function onUploadStart(event) {

}

// Do something on each file's upload progress event.
function onUploadProgress(event) {
    rowNum = fileIdHash[event["id"]];
    prog = Math.round(100 * (event["bytesLoaded"] / event["bytesTotal"]));
    progbar = "<div style='height:5px;width:100px;background-color:#CCC;'><div style='height:5px;background-color:#F00;width:"
            + prog + "px;'></div></div>";
    singleSelectDataTable.updateRow(rowNum, {
        name : dataArr[rowNum]["name"],
        size : dataArr[rowNum]["size"],
        progress : progbar
    });
}

// Do something when each file's upload is complete.
function onUploadComplete(event) {
    rowNum = fileIdHash[event["id"]];
    prog = Math.round(100 * (event["bytesLoaded"] / event["bytesTotal"]));
    progbar = "<div style='height:5px;width:100px;background-color:#CCC;'><div style='height:5px;background-color:#62CF40;width:100px;'></div></div>";
    singleSelectDataTable.updateRow(rowNum, {
        name : dataArr[rowNum]["name"],
        size : dataArr[rowNum]["size"],
        progress : progbar
    });
    if (rowNum == singleSelectDataTable.getRecordSet().getLength() - 1) {
        singleSelectDataTable.deleteRows(0, singleSelectDataTable.getRecordSet().getLength());
        singleSelectDataTable.destroy();
        uploader.clearFileList();
        if (uploader.parentObject.callback){
            uploader.parentObject.callback(uploader);
        }
    }
}
function onUploadError(event) {
    alert ('Upload Failure!');
}
function onUploadCancel(event) {
}
function onUploadResponse(event) {
    if (!event.data){
        alert ('Server answer is empty!');
        return;
    }
    return phpmyhandleSuccess({ responseText: event.data});

}
function yuiUploaderUploadResetList() {
    singleSelectDataTable.destroy();
    uploader.clearFileList();
}